<?php

namespace app\admin\model\order;

use app\admin\model\user\UserModel;
use app\api\model\order\OrderMusicDetailApiModel;
use app\logic\model\order\OrderMusicLogicModel;
use app\logic\model\user\UserLogicModel;
use app\logic\single\EntitySingle;

class OrderMusicModel extends OrderMusicLogicModel
{
    public function getList(\think\Request $request, array $where, string $field='*', $page = 1, $limit=15,$order='id desc')
    {
        $query=$this->where($where)
            ->where(function ($q) use ($request){
                if(check_request($request,'status')){
                    $q->whereLike("status",$request['status']);
                }
                if(check_request($request,'user')){
                    $q->whereIn("buyer_id",UserLogicModel::getIdsByName($request['user']));
                }
                if(check_request($request,'writer_can_see')){
                    $order_id = OrderMusicDetailApiModel::where('writer_can_see',-1)
                        ->column('order_id');
                    $q->whereIn("id",array_unique($order_id));
                }
                if(check_request($request,'start_time')&&check_request($request,'end_time')){
                    $q->whereBetween("create_time",[$request['start_time'],$request['end_time']." 23:59:59"]);
                }elseif (check_request($request,'start_time')){
                    $q->where("create_time",">=",$request['start_time']);
                }elseif (check_request($request,'end_time')){
                    $q->where("create_time","<=",$request['end_time']." 23:59:59");
                }
            });
        $list = $query->field($field)->order($order)->page($page,$limit)->select();
        $count = $query->count();
        if($count>0){
            $list = $list->toArray();
            $buyer_id = array_column($list,'buyer_id');
            $users = UserModel::getInfosByIds($buyer_id);
            foreach ($list as &$val){
                $val['detail'] = OrderMusicDetailApiModel::getByOrderId($val['id']);
                $val['writer_can_see'] = 1;
                foreach ($val['detail'] as $d_val){
                    if($d_val['sell_id']>0 && $d_val['writer_can_see'] ==-1 ){
                        $val['writer_can_see'] = -1;
                    }
                }
                $val['buyer'] = $users[$val['buyer_id']]??[];
            }
        }
        return [$list,$count];
    }
}